package com.kingwood.algorithm.test;

/**
 * @Author 22025812
 * @Description: TODO
 * @Date: 2024/2/26 13:35
 * @Modified By：
 * @Version 1.0
 */
public class NumberPrint {

    /**
     * 螺旋数字打印
     * @param n
     * @param m
     */
    public static void printNumber(int n, int m) {
        if (n <= 0 || m <= 0) {
            return;
        }

        // n 数字 m 行数
        if (n <= m) {
            for (int i = 1; i <= n; i++) {
                System.out.println(i);
            }
            for (int i = n + 1; i<=m; i++) {
                System.out.println("*");
            }

            return;
        }

        // 确定列数 m行数, col 列数
        int col = n / m + 1;
        int leftUpRow = 0;
        int leftUpCol = 0;
        int rightDownRow = m - 1;
        int rightDownCol = col - 1;
        int count = 1;
        int[][] arr = new int[m][col];

        while (leftUpRow <= rightDownRow && leftUpCol <= rightDownCol) {
            if (leftUpRow == rightDownRow && leftUpCol == rightDownCol) {
                arr[leftUpRow][leftUpCol] = count;
                break;
            }

            // 一条横线
            if (leftUpRow == rightDownRow) {
                for (int i = leftUpCol; i <= rightDownCol; i++) {
                    arr[leftUpRow][i] = count;
                    count++;
                }
            }
            // 一条竖线
            else if (leftUpCol == rightDownCol) {
                for (int i = leftUpRow; i <= rightDownRow; i++) {
                    arr[i][leftUpCol] = count;
                    count++;
                }
            } else {
                for (int i = leftUpCol; i < rightDownCol; i++) {
                    arr[leftUpRow][i] = count;
                    count++;
                }
                for (int i = leftUpRow; i < rightDownRow; i++) {
                    arr[i][rightDownCol] = count;
                    count++;
                }
                for (int i = rightDownCol; i > leftUpCol; i--) {
                    arr[rightDownRow][i] = count;
                    count++;
                }
                for (int i = rightDownRow; i > leftUpRow; i--) {
                    arr[i][leftUpCol] = count;
                    count++;
                }
            }

            leftUpRow++;
            leftUpCol++;
            rightDownRow--;
            rightDownCol--;
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < col; j++) {
                int val = arr[i][j];
                if (val > n) {
                    System.out.print("*  ");
                } else {
                    System.out.print(arr[i][j] + " ");
                }
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        printNumber(130, 7);
    }
}
